<template>
  <div class="components-activity-add-or-update">
    <el-dialog
      v-model="visible"
      :modal-append-to-body="false"
      :title="
        !dataForm.groupActivityId
          ? $t('groups.newJoinGroupActivity')
          : $t('groups.editGroupActivities')
      "
      :close-on-click-modal="false"
      :before-close="cancelBtn"
      width="50%"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="145px"
        @submit.prevent
      >
        <el-form-item
          :label="$t('groups.eventName')"
          prop="activityName"
        >
          <el-input
            v-model="dataForm.activityName"
            :placeholder="$t('groups.enterEventName')"
            maxlength="30"
            show-word-limit
            :disabled="dataForm.activityStatus > 2 && dataForm.activityStatus !== 5"
            class="groupActivity-input"
            style="width: 524px; max-width: 100%"
          />
        </el-form-item>
        <el-form-item
          :label="$t('group.actTime')"
          prop="startTime"
        >
          <el-date-picker
            v-model="dataForm.startTime"
            :disabled="
              (dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false) || pickerDisabled
            "
            value-format="YYYY-MM-DD"
            type="date"
            style="width: 145px"
            :placeholder="$t('marketing.chooseStartTime')"
          />
          <el-time-select
            v-model="startTimeValue"
            start="00:00"
            step="00:30"
            end="23:30"
            style="width: 105px"
            :class="{'time-select': true, 'time-select-clear': !!startTimeValue}"
            :disabled="
              (dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false) || pickerDisabled
            "
            :placeholder="$t('user.startDate')"
          />
          <span style="margin: 0 10px">-</span>
          <el-date-picker
            v-model="dataForm.endTime"
            :disabled="
              (dataForm.activityStatus
                ? dataForm.activityStatus > 2 && dataForm.activityStatus !== 5
                : false) || pickerDisabled
            "
            value-format="YYYY-MM-DD"
            type="date"
            style="width: 145px"
            :placeholder="$t('marketing.chooseEndTime')"
          />
          <el-time-select
            v-model="endTimeValue"
            start="00:00"
            step="00:30"
            end="23:30"
            style="width: 105px"
            :class="{'time-select': true, 'time-select-clear': !!endTimeValue}"
            :disabled="
              (dataForm.activityStatus
                ? dataForm.activityStatus > 2 && dataForm.activityStatus !== 5
                : false) || pickerDisabled
            "
            :placeholder="$t('user.endDate')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('group.groupNum')"
          prop="groupNumber"
        >
          <el-input
            v-model="dataForm.groupNumber"
            type="number"
            min="2"
            max="1000000000"
            :disabled="
              dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false
            "
            style="width: 524px; max-width: 100%"
            class="groupActivity-input"
            @change="groupNumCheck"
          >
            <template #append>
              {{ $t('groups.people') }}
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('groups.groupValidityPeriod')"
          prop="groupValidTime"
        >
          <el-input
            v-model="dataForm.groupValidTime"
            type="number"
            :disabled="
              dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false
            "
            class="groupActivity-input"
            style="width: 524px; max-width: 100%"
            :min="0"
            onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
          >
            <template #append>
              {{ $t('groups.minute') }}
            </template>
          </el-input>

          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('groups.tip4')"
            placement="right"
          >
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
        <el-form-item
          :label="$t('groups.limitPurchase')"
          prop="hasMaxNum"
        >
          <el-radio-group
            v-model="dataForm.hasMaxNum"
            :disabled="
              dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false
            "
          >
            <el-radio :label="0">
              {{ $t('station.close') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('groups.turnOn') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="dataForm.hasMaxNum"
          :label="$t('product.maxNum')"
          prop="maxNum"
        >
          <el-input
            v-model="dataForm.maxNum"
            type="number"
            :disabled="
              dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false
            "
            min="1"
            max="100000000"
            class="groupActivity-input"
            @change="maxNumCheck"
          >
            <template #append>
              {{ $t('groups.memberPeople') }}
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('groups.simulation')"
          prop="hasRobot"
        >
          <div>
            <el-radio-group
              v-model="dataForm.hasRobot"
              :disabled="
                dataForm.activityStatus
                  ? dataForm.activityStatus > 2 && dataForm.activityStatus !== 5
                  : false
              "
            >
              <el-radio :label="0">
                {{ $t('station.close') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('groups.turnOn') }}
              </el-radio>
            </el-radio-group>
            <div class="auxiliary-font">
              <span>{{ $t('groups.tip5') }} </span>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('groups.groupMode')"
          prop="hasGroupTip"
        >
          <el-radio-group
            v-model="dataForm.hasGroupTip"
            :disabled="
              dataForm.activityStatus
                ? dataForm.activityStatus > 2 && dataForm.activityStatus !== 5
                : false
            "
          >
            <el-radio :label="0">
              {{ $t('station.close') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('groups.turnOn') }}
            </el-radio>
          </el-radio-group>
          <div class="auxiliary-font">
            {{ $t('groups.tip8') }}
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('groups.activityWarmUp')"
          prop="isPreheat"
        >
          <el-radio-group
            v-model="dataForm.isPreheat"
            :disabled="
              (dataForm.activityStatus
                ? dataForm.activityStatus !== 1 && dataForm.activityStatus !== 5
                : false) || showEventPreview
            "
          >
            <el-radio :label="0">
              {{ $t('station.close') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('groups.turnOn') }}
            </el-radio>
          </el-radio-group>
          <div class="auxiliary-font">
            {{ $t('groups.tip9') }}
          </div>
        </el-form-item>
        <!-- 商品选择框 -->
        <el-form-item
          :label="$t('group.selectProd')"
          prop="prodId"
        >
          <el-button
            v-if="!dataForm.prodId"
            class="tips-button"
            :disabled="+dataForm.status === 5 && dataForm.groupActivityId != null"
            @click="onSelectProd"
          >
            {{ $t('group.selectProd') }}
            <el-tooltip
              :content="$t('groups.tip10')"
              placement="top"
              class="tips"
              style="position: absolute; margin-left: 3px"
            >
              <el-icon
                class="question-filled"
              >
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </el-button>
          <!-- 商品 -->
          <div
            v-if="dataForm.prodId"
            style="display: flex; margin-bottom: 20px"
          >
            <el-card
              v-for="item in spus"
              :key="item.skuId"
              :body-style="{ padding: '0px' }"
              style="height: 160px; width: 120px; margin-right: 5px"
            >
              <ImgShow
                :src="item.pic"
                style="height: 104px; width: 100%"
              />
              <div class="card-prod-bottom card-prod-d">
                <span class="card-prod-name">{{ item.skuName }}</span>
                <el-button
                  v-if="!dataForm.groupActivityId"
                  type="primary"
                  link
                  class="card-prod-name-buttons"
                  @click="deleteCurrentProd()"
                >
                  删除
                </el-button>
              </div>
            </el-card>
          </div>
        </el-form-item>
        <!-- 商品sku列表 -->
        <div v-if="dataForm.groupSkuList && dataForm.groupSkuList.length > 0">
          <el-table
            :data="dataForm.groupSkuList"
            border
            header-cell-class-name="table-header"
            row-class-name="table-row"
          >
            <el-table-column :label="dataForm.groupSkuList.length > 1 ? 'sku名称' : '商品名称'">
              <template #default="scope">
                <span>{{
                  dataForm.groupSkuList.length > 1 ? scope.row.skuName : spus[0].skuName
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="活动价格">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.actPrice"
                  :disabled="
                    !(dataForm.groupActivityId == null || +dataForm.status === 2) ||
                      scope.row.status !== 1
                  "
                  :min="0.01"
                  :step="1"
                  :max="scope.row.price"
                  class="groupActivity-input"
                  @change="actPriceChange(scope.$index, $event)"
                  @blur="actPriceBlur"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="cancelBtn()"
          >
            {{ $t('crud.filter.cancelBtn') }}
          </div>
          <div
            v-if="
              (dataForm.status !== 0 && dataForm.status !== 5) || dataForm.groupActivityId == null
            "
            class="default-btn primary-btn"
            type="primary"
            @click="onSubmit()"
          >
            {{ $t('groups.submit') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 商品选择弹窗  测试完之后添加这个链接  dataUrl='/group/prod/getNotGroupProdPage'-->
    <prods-select
      v-if="groupSelectProdVisible"
      ref="ProdsSelectRef"
      :is-single="true"
      :prod-type="0"
      @refresh-select-prods="selectGroupProds"
    />
  </div>
</template>

<script setup>
import ProdsSelect from '@/components/prods-select/index.vue'
import { Debounce } from '@/utils/debounce'
import { getDateTimeRange, getParseTime } from '@/utils/datetime'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])
const dataFormRef = ref(null)

const visible = ref(false)
const pickerDisabled = ref(false)
const showEventPreview = ref(false)
const groupSelectProdVisible = ref(false)
const validEndTime = ref([])
// dialogWidth:'895px'
const dataForm = ref({
  groupActivityId: null,
  shopId: null,
  activityName: null,
  status: null,
  startTime: null,
  endTime: null,
  groupValidTime: null,
  groupNumber: null,
  hasMaxNum: 0,
  maxNum: null,
  hasRobot: 0,
  hasLeaderPrice: 0,
  isPreheat: 0,
  hasGroupTip: 1,
  groupOrderCount: null,
  groupNumberCount: null,
  createTime: null,
  updateTime: null,
  groupProds: [],
  validEndTime: [],
  groupSkuList: []
})
const spus = ref([])
const isSubmit = ref(false)

// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  if (!startTimeValue.value || !dataForm.value.startTime) {
    callback(new Error($t('groups.startTimeCannotBeEmpty')))
  }
  if (!endTimeValue.value || !dataForm.value.endTime) {
    callback(new Error($t('groups.endTimeCannotBeEmpty')))
  }
  const startTime = dataForm.value.startTime + ' ' + startTimeValue.value + ':00'
  const endTime = dataForm.value.endTime + ' ' + endTimeValue.value + ':00'
  showEventPreview.value = Date.parse(startTime) < Date.parse(new Date())
  if (dataForm.value.status !== 5 && rule.field === 'endTime' && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  }
  if (Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('groups.endTimeIsTooSmall')))
  } else if (
    dataForm.value.status === 1 &&
    dataForm.value.groupActivityId &&
    Date.parse(validEndTime) > Date.parse(endTime)
  ) {
    callback(new Error($t('groups.extendedEndTime')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateGroupNumber = (rule, value, callback) => {
  if (dataForm.value.groupNumber < 2) {
    callback(new Error($t('groups.tip1')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateactivityName = (rule, value, callback) => {
  if (!dataForm.value.activityName.trim()) {
    callback(new Error($t('groups.pleaseEnterEventName')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateGroupValidTime = (rule, value, callback) => {
  if (dataForm.value.groupValidTime < 15) {
    callback(new Error($t('groups.tip2')))
  } else if (dataForm.value.groupValidTime > 24 * 60) {
    callback(new Error($t('groups.tip3')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  activityName: [
    { required: true, message: $t('groups.pleaseEnterEventName'), trigger: 'blur' },
    { validator: validateactivityName, trigger: 'blur' }
  ],
  maxNum: [{ required: true, message: $t('groups.pleaseEnterEventNum'), trigger: 'blur' }],
  groupNumber: [
    { required: true, message: $t('groups.pleaseEnteNumGrp'), trigger: 'blur' },
    { validator: validateGroupNumber, trigger: 'blur' }
  ],
  groupValidTime: [
    { required: true, message: $t('groups.pleaseEnterTimeGroup'), trigger: 'blur' },
    { validator: validateGroupValidTime, trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('groups.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ]
})
const startTimeValue = ref('')
const endTimeValue = ref('')
watch(() => startTimeValue.value, () => {
  if (dataFormRef.value?.validateField) {
    dataFormRef.value.validateField('startTime')
  }
})

const init = groupActivityId => {
  dataForm.value.groupSkuList = []
  dataForm.value.groupActivityId = groupActivityId || null
  dataForm.value.activityStatus = null
  visible.value = true
  pickerDisabled.value = false
  isSubmit.value = false
  nextTick(() => {
    dataFormRef.value.resetFields()
    const datetimeRange = getDateTimeRange()
    dataForm.value.startTime = datetimeRange.startTime
    dataForm.value.endTime = datetimeRange.endTime
    startTimeValue.value = datetimeRange.currentTime
    endTimeValue.value = datetimeRange.currentTime
    if (dataForm.value.groupActivityId) {
      http({
        url: http.adornUrl('/group/activity/info/' + dataForm.value.groupActivityId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        spus.value = [
          {
            skuName: data.prodName,
            pic: data.prodPic
          }
        ]
        showEventPreview.value = Date.parse(data.startTime) < Date.parse(new Date())
        dataForm.value = data
        startTimeValue.value = dataForm.value.startTime ? dataForm.value.startTime.substring(11, dataForm.value.startTime.length - 3) : ''
        endTimeValue.value = dataForm.value.endTime ? dataForm.value.endTime.substring(11, dataForm.value.endTime.length - 3) : ''
        dataForm.value.startTime = getParseTime(dataForm.value.startTime, '{y}-{m}-{d}')
        dataForm.value.endTime = getParseTime(dataForm.value.endTime, '{y}-{m}-{d}')
        validEndTime.value = data.endTime
      })
    }
  })
}
// 表单提交
const onSubmit = Debounce(() => {
  dataFormRef.value.validate(valid => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      if (!dataForm.value.prodId) {
        return ElMessage.error('请选择商品')
      }
      const startTime = dataForm.value.startTime
      const endTime = dataForm.value.endTime
      dataForm.value.startTime =
        dataForm.value.startTime && startTimeValue ? dataForm.value.startTime + ' ' + startTimeValue.value + ':00' : ''
      dataForm.value.endTime =
        dataForm.value.endTime && endTimeValue ? dataForm.value.endTime + ' ' + endTimeValue.value + ':00' : ''
      isSubmit.value = true
      pickerDisabled.value = true
      const submitForm = toRaw(dataForm.value)
      http({
        url: http.adornUrl('/group/activity'),
        method: dataForm.value.groupActivityId ? 'put' : 'post',
        data: http.adornData(submitForm)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            isSubmit.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit.value = false
        pickerDisabled.value = false
      })
      dataForm.value.startTime = startTime
      dataForm.value.endTime = endTime
    }
  })
})
// 选择商品操作
const ProdsSelectRef = ref(null)
const onSelectProd = () => {
  groupSelectProdVisible.value = true
  nextTick(() => {
    ProdsSelectRef.value.init(dataFormRef.value?.groupProds)
  })
}
// 选商品回调
const selectGroupProds = prods => {
  prods = prods[0]
  if (prods) {
    dataForm.value.prodId = prods.prodId
    const prodIds = []
    dataForm.value.groupProds = prods
    spus.value = [
      {
        skuName: prods.prodName,
        pic: prods.pic
      }
    ]
    prodIds.push(prods.prodId)

    getProdAndSkuListsByProdIds(prodIds)
  }
}
const groupNumCheck = () => {
  let maxNum = Math.round(dataForm.value.groupNumber)
  if (!maxNum) {
    maxNum = 2
  } else if (maxNum < 2) {
    maxNum = 2
  } else if (maxNum > 500) {
    maxNum = 500
  }
  dataForm.value.groupNumber = maxNum
}
const maxNumCheck = () => {
  let maxNum = Math.round(dataForm.value.maxNum)
  if (!maxNum) {
    maxNum = 1
  } else if (maxNum < 1) {
    maxNum = 1
  } else if (maxNum > 1000000000) {
    maxNum = 1000000000
  }
  dataForm.value.maxNum = maxNum
}
// 通过商品id列表，查询所有的对应的sku列表
const getProdAndSkuListsByProdIds = prodIds => {
  if (prodIds) {
    http({
      url: http.adornUrl('/sku/getAllSkuList'),
      method: 'get',
      params: {
        prodId: prodIds.join()
      }
    }).then(({ data }) => {
      dataForm.value.groupSkuList = dataForm.value.groupSkuList || []
      for (let index = 0; index < data.length; index++) {
        const obj = {
          actPrice: data[index].price,
          // groupSkuId: item.,
          pic: data[index].pic,
          price: data[index].price,
          properties: data[index].properties,
          sellNum: data[index].actualStock - data[index].stocks,
          skuId: data[index].skuId,
          skuName: data[index].skuName,
          status: data[index].status
        }
        dataForm.value.groupSkuList.push(obj)
      }
    })
  }
}
/**
 * 删除商品
 */
const deleteCurrentProd = () => {
  spus.value = []
  dataForm.value.groupSkuList = []
  dataForm.value.prodId = null
}
// 关闭对话框
const cancelBtn = () => {
  deleteCurrentProd()
  visible.value = false
}
const actPriceBlur = () => {
  dataForm.value.groupSkuList.forEach(item => {
    if (!item.actPrice) item.actPrice = 0.01
  })
}

defineExpose({
  init
})
</script>
<style lang="scss" scoped>
:deep(.el-input__inner) {
  border: none !important;
  padding-left: 0 !important;
}
.components-activity-add-or-update {
  .card-prod-bottom{
    position: relative;
    text-align: left;
    .card-prod-name{
      margin: auto;
      padding: 0 6px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 118px;
      display: inline-block;
    }
    .card-prod-name-buttons{
      position: absolute;
      top: 24px;
      right: 10px;
      font-size: 12px;
    }
  }
  .groupActivity-input {
    width: 60%;
  }

  .auxiliary-font {
    font-size: 12px;
    color: #cbc0cb;
    line-height: 20px;
  }
  :deep(.time-select.el-select ){
    .el-input .el-select__caret.el-icon{
      display: none;
    }
    &.time-select-clear:hover .el-input .el-select__caret.el-icon{
      display: flex;
    }
  }
}
.tips-button .question-filled{
  margin-left: 3px;
}
:deep(.el-form-item__content) {
  display: block;
}
</style>
